<template>
    <div class="user-manage">
        <div class="manage-search">
            <yh-input placeholder="编号/账号/昵称" v-model="searchParams.keyOrName" size="mini"></yh-input>
            <yh-button type="primary" size="mini" @click="search"> 查询 </yh-button>
            <yh-button type="primary" size="mini" v-authCode.show="B_0192" @click="addDialog">新增 </yh-button>
            <yh-button type="danger" size="mini" v-authCode.show="B_0194" @click="getUserInfo()">删除</yh-button>
        </div>
        <div class="user-tables">
            <!-- 表格 -->
            <div class="user-tables-div noOpened">
                <RiskTableP
                    ref="multipleTable"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :column="tableColumns"
                    :searchParams="searchParams"
                    :paging="paging"
                    v-loading="tableLoading"
                    @page-change="getTableData"
                    :checkMethod="checkMethod"
                >
                    <!-- '1': '新增用户','2': '修改用户','3': '删除用户','4': '调整产品权限','5': '调整锁定状态','6': '用户同步',  -->
                    <template #userCode="{ row }">
                        <span v-if="['2', '4', '5', '6'].includes(row.modifyType) && row.modifyStatus === '1'">
                            <i class="el-icon-setting" />{{ row.userCode }}
                        </span>
                        <span v-else-if="row.modifyType === '3' && row.modifyStatus === '1'"> <i class="el-icon-delete" />{{ row.userCode }} </span>
                        <span v-else-if="row.modifyType === '1' && row.modifyStatus === '1'">
                            <i class="el-icon-folder-add" />{{ row.userCode }}
                        </span>
                        <span v-else>
                            {{ row.userCode }}
                        </span>
                    </template>
                    <template #userEnable="{ row }">
                        <span :style="getTextColor('userEnable', row.userEnable)">{{ Dict.userEnablePojo[row.userEnable] || '--' }}</span>
                    </template>
                    <template #jobStatus="{ row }">
                        <span :style="getTextColor('jobStatus', row.jobStatus)">{{ Dict.jobStatusPojo[row.jobStatus] || '--' }}</span>
                    </template>
                    <template #lockType="{ row }">
                        <span :style="getTextColor('lockType', row.lockType)">{{ Dict.lockTypePojo[row.lockType] || '未锁定' }}</span>
                    </template>
                    <template #operation="{ row }">
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            title="编辑"
                            v-authCode="B_0193"
                            :disabled="row.modifyStatus == '1' && row.modifyType == '3'"
                            @on-click="lookEditorInfo(row)"
                        ></RiskIconButton>
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-setting"
                            size="mini"
                            :disabled="row.superuser || (row.modifyStatus == '1' && row.modifyType == '3')"
                            v-authCode="B_0195"
                            title="权限设置"
                            @on-click="jurisdictionInfo(row)"
                        ></RiskIconButton>
                        <RiskIconButton
                            type="primary"
                            :disabled="row.superuser || (row.modifyStatus == '1' && row.modifyType == '3')"
                            icon="yh-reset-password"
                            v-authCode="B_0370"
                            topTitle="用户访问控制"
                            size="mini"
                            @on-click="accessControl(row)"
                        ></RiskIconButton>
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-printer"
                            v-authCode="B_0371"
                            topTitle="用户修改记录"
                            size="mini"
                            @on-click="operateRecord(row)"
                        ></RiskIconButton>
                        <RiskIconButton
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            title="删除"
                            :disabled="row.superuser || row.modifyStatus == '1'"
                            v-authCode="B_0194"
                            @on-click="getUserInfo(row.userCode)"
                        ></RiskIconButton>
                    </template>
                </RiskTableP>
            </div>
            <!-- 新增 -->
            <div v-if="dialogAdd">
                <yh-dialog drag title="新增用户" :visible.sync="dialogAdd" v-loading="addLoading" width="500px" :close-on-click-modal="false">
                    <div class="user-list-dialog">
                        <el-form ref="form" label-width="145px" size="mini">
                            <el-form-item label="用户编号">
                                <el-input
                                    placeholder="自动生成"
                                    size="mini"
                                    :disabled="true"
                                    v-model="addData.userCode"
                                    class="list-dialog-form"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="用户昵称" required>
                                <el-input size="mini" v-model="addData.userNickName" class="list-dialog-form"></el-input>
                            </el-form-item>
                            <el-form-item label="用户账号" required>
                                <el-select
                                    v-model="addData.userName"
                                    filterable
                                    :filter-method="getuserCodeList"
                                    size="mini"
                                    clearable
                                    style="width: 77%"
                                    v-if="WEB_DOCKING == 'SINOSIG'"
                                >
                                    <el-option v-for="i in userReport" :key="i.userName" :label="i.userName" :value="i.userName"> </el-option>
                                </el-select>
                                <el-input size="mini" v-model="addData.userName" class="list-dialog-form" v-else></el-input>
                            </el-form-item>
                            <el-form-item label="用户密码" required v-if="WEB_DOCKING != 'SINOSIG'">
                                <el-input size="mini" v-model="passWord" class="list-dialog-form" show-password></el-input>
                            </el-form-item>
                            <el-form-item label="用户邮箱" required>
                                <el-input size="mini" class="list-dialog-form" v-model="addData.email"></el-input>
                            </el-form-item>
                            <el-form-item label="角色">
                                <RiskCustomSelect
                                    :dataSource="roleStorage"
                                    :selectKeys="addRole"
                                    class="list-dialog-form"
                                    @customSelectReturn="customSelectReturn($event, 'add')"
                                    :key="addRoleKeyNum + 'addRoleKeyNum'"
                                    :disabled="addData.superuser"
                                ></RiskCustomSelect>
                            </el-form-item>

                            <el-form-item label="主题" required>
                                <el-select size="mini" class="list-dialog-form" v-model="addData.themeType">
                                    <el-option v-for="item in themeData" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="启用状态" required>
                                <el-switch
                                    size="mini"
                                    active-color="#13ce66"
                                    inactive-color="#eee"
                                    active-value="1"
                                    inactive-value="0"
                                    v-model="addData.userEnable"
                                >
                                </el-switch>
                            </el-form-item>

                            <el-form-item label="超级管理员" v-if="userInfo.superuser">
                                <el-switch
                                    size="mini"
                                    active-color="#13ce66"
                                    inactive-color="#eee"
                                    v-model="addData.superuser"
                                    @change="changeSuperUser($event, 'add')"
                                >
                                </el-switch>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="dialogAdd = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="addUserInfo">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>
            <!-- 编辑 -->
            <div class="user-tables-editor">
                <yh-dialog drag title="编辑用户" :visible.sync="dialogEditor" width="500px" v-loading="editLoading" :close-on-click-modal="false">
                    <div class="user-list-dialog">
                        <el-form ref="form" :model="editData" label-width="145px" size="mini">
                            <el-form-item label="用户编号">
                                <el-input
                                    placeholder="自动生成"
                                    size="mini"
                                    :disabled="true"
                                    v-model="editData.userCode"
                                    class="list-dialog-form"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="用户昵称" required>
                                <el-input size="mini" class="list-dialog-form" v-model="editData.userNickName"></el-input>
                            </el-form-item>
                            <el-form-item label="用户账号" required>
                                <el-input size="mini" class="list-dialog-form" v-model="editData.userName" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="用户密码" v-if="WEB_DOCKING != 'SINOSIG'">
                                <el-tooltip placement="bottom">
                                    <div slot="content">为空是则认为不改密码</div>
                                    <el-input
                                        size="mini"
                                        class="list-dialog-form"
                                        show-password
                                        v-model="editData.password"
                                        placeholder="为空是则认为不改密码"
                                        @input="$forceUpdate()"
                                    ></el-input>
                                </el-tooltip>
                            </el-form-item>
                            <el-form-item label="用户邮箱" required>
                                <el-input size="mini" class="list-dialog-form" v-model="editData.email"></el-input>
                            </el-form-item>
                            <el-form-item label="角色">
                                <RiskCustomSelect
                                    :dataSource="computedRoleStorage"
                                    :selectKeys="editRole"
                                    class="list-dialog-form"
                                    @customSelectReturn="customSelectReturn($event, 'edit')"
                                    :key="roleKeyNum + 'roleKey'"
                                    :disabled="editData.superuser"
                                ></RiskCustomSelect>
                            </el-form-item>
                            <el-form-item label="主题" required>
                                <el-select size="mini" class="list-dialog-form" v-model="editData.themeType">
                                    <el-option v-for="item in themeData" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="启用状态" required>
                                <el-switch
                                    size="mini"
                                    active-color="#13ce66"
                                    inactive-color="#eee"
                                    active-value="1"
                                    inactive-value="0"
                                    v-model="editData.userEnable"
                                    :disabled="WEB_DOCKING == 'SINOSIG' && editData.lockType == '0'"
                                >
                                </el-switch>
                            </el-form-item>
                            <el-form-item label="超级管理员" v-if="userInfo.superuser">
                                <el-switch
                                    size="mini"
                                    active-color="#13ce66"
                                    inactive-color="#eee"
                                    v-model="editData.superuser"
                                    @change="changeSuperUser($event, 'edit')"
                                >
                                </el-switch>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="dialogEditor = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="editUserInfo">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>
            <!-- 删除 -->
            <div>
                <yh-dialog
                    drag
                    title="删除用户（已自动过滤管理员账号）"
                    :visible.sync="removeAlert"
                    width="500px"
                    v-loading="editLoading"
                    :close-on-click-modal="false"
                >
                    <div class="remove-text">
                        <span>{{ deleteCode.join(' , ') }}</span>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="removeAlert = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="removeUserInfo">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>
            <!-- 权限设置 -->
            <div class="user-qx">
                <yh-dialog drag title="权限设置" :visible.sync="dialogJurisdiction" width="850px" v-loading="Loading" :close-on-click-modal="false">
                    <!-- <span slot="label">
                        <i class="el-icon-tickets"></i>
                        产品权限
                    </span> -->
                    <div class="uers-tabs">
                        <el-checkbox v-model="isDisabled" style="margin: 10px 20px; font-weight: 700">是否拥有所有产品权限</el-checkbox>
                        <RiskTrantable
                            ref="usertrantable"
                            leftPlaceholder="编码/名称"
                            :leftColumns="tranColmens"
                            :leftTableData="leftTranData"
                            :rightTableData="rightTranData"
                            indexKey="fundCode"
                            :leftSearchNames="['fundCode', 'fundName']"
                            :isDisabled="isDisabled"
                        />
                    </div>
                    <!-- <yh-tabs type="border-card">
                        <yh-tab-pane label="用户管理">
                            <span slot="label">
                                <i class="el-icon-tickets"></i>
                                用户管理
                            </span>
                            <div class="uers-tabs">
                                <yh-tree
                                    :data="treeData"
                                    show-checkbox
                                    node-key="resourceCode"
                                    ref="tree"
                                    highlight-current
                                    :props="{
                                        children: 'children',
                                        label: 'resourceName',
                                    }"
                                ></yh-tree>
                            </div>
                        </yh-tab-pane>
                        <yh-tab-pane label="产品权限">

                        </yh-tab-pane>
                    </yh-tabs> -->

                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="dialogJurisdiction = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="editUserclick">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>

            <!-- 用户访问控制 -->
            <AccessControl
                :dialog="accessControlVisible"
                :userInfo="currentUserInfo"
                v-if="accessControlVisible"
                @close-custom="accessControlRet"
            ></AccessControl>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Emit, Model, Prop, Vue } from 'vue-property-decorator';
import { addUserData, resourceList } from './tables';
import md5 from 'js-md5';
import { AuthenticationMd5Key, getUser } from '@/utils/user-util';
import { getCurrentPageData, timeFormat, dateFormat, changeOptions, getConfigItem } from '@/utils/tools';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import RiskCustomSelect from '@/common/components/risk-custom-select.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import Dict from '../dict/user-check';
import DictionConstUtil from '@/utils/diction-const-util';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import { TableConfigVO } from '@/common/vo';
import AccessControl from './access-control.vue';
import API from '../api/auth-manage';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import { mixins } from 'vue-class-component';
@Component({
    name: 'UserList',
    components: {
        RiskTrantable,
        RiskCustomSelect,
        RiskPagination,
        RiskTableP,
        RiskIconButton,
        AccessControl,
    },
})
export default class UserList extends mixins(RiskEmitter) {
    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    Dict = new Dict();
    // 列表展示数据
    private tableData: any[] = [];

    // 过滤后的数据
    private dialogEditor: boolean = false;
    private dialogJurisdiction: boolean = false;
    private dialogAdd: boolean = false;
    private addLoading: boolean = false;
    private editLoading: boolean = false;
    private removeAlert: boolean = false;
    private Loading: boolean = false;

    paging: any = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    private passWord: string = '';
    private deleteCode: any[] = [];
    private roleKeyNum: number = 0;
    private addRoleKeyNum: number = 0;
    private riskTrantableKey: number = 0;
    private isDisabled: boolean = false;

    private themeData: resourceList[] = [
        { id: '1', name: '浅色' },
        { id: '0', name: '深色' },
    ];

    private editData: addUserData = {
        userCode: '',
        userName: '',
        superuser: false,
        userNickName: '',
        password: '',
        email: '',
        userEnable: '1',
        themeType: '0',
        role: '',
        roleCodes: [], // 后端实际使用字段
    };
    private addData: addUserData = {
        userCode: '',
        userName: '',
        superuser: false,
        userNickName: '',
        password: '',
        email: '',
        userEnable: '1',
        themeType: '0',
        role: '',
        roleCodes: [], // 后端实际使用字段
    };
    // tree数据
    private treeData: any[] = [
        {
            children: [],
            label: '',
            createDate: 0,
            createTime: 0,
            menuIcon: '',
            menuUrl: '',
            parentValid: false,
            resourceCode: '',
            resourceName: '',
            resourceParentCode: '',
            show: false,
            sort: 0,
            sourceType: '',
        },
    ];
    // 角色
    private addRole: any[] = [];
    private editRole: any[] = [];
    private userCode: string = '';
    // 排除父级数据
    private menuAllOut: any[];
    private menuAllList: any[];
    // 穿梭框数据
    private tranColmens: any[] = [
        {
            label: '编号',
            prop: 'fundCode',
            width: 70,
        },
        {
            label: '名称',
            prop: 'fundName',
        },
    ];
    private leftTranData: any[] = [
        {
            id: '',
            fundCode: '',
            fundName: '',
        },
    ];

    private rightTranData: any[] = [
        {
            id: '',
            fundCode: '',
            fundName: '',
        },
    ];

    private userCodeList: any[] = [];

    private roleStorage: any[] = []; // 角色仓库

    private userInfo = getUser();
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'userCode',
    };
    tableColumns = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        { field: 'userCode', title: '用户编号', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        { field: 'userName', title: '用户账号', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        { field: 'userNickName', title: '用户昵称', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        // {
        //     field: 'password',
        //     title: '密码',
        //     minWidth: '120px',
        //     align: 'center',
        //     render: value => '*** ** ***',
        // },
        {
            field: 'superuser',
            title: '管理员',
            sortable: true,
            minWidth: '120px',
            align: 'center',
            filterType: 'funnel',
            filterField: 'isSuppers',
            filters: DictionConstUtil.PojoToList3(this.Dict.isOrNotPojoS),
            render: value => this.Dict.isOrNotPojoB[value],
        }, // true 是  false否
        {
            field: 'roleName2',
            title: '角色',
            align: 'center',
            sortable: true,
            sortField: 'roleName',
            minWidth: '120px',
            filterType: 'search',
            filterField: 'roleName',
            //  TODO  确认查询字段
            filters: [{ data: '' }],
            // filterType: 'funnel',
            // filters: this.roleStorage.map(item => {
            //     return { value: item.dictKey, label: item.dictKeyName };
            // }),
        }, //  数组形式处理  TODO
        {
            field: 'userEnable',
            title: '启用状态',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'userEnables',
            filters: DictionConstUtil.PojoToList3(this.Dict.userEnablePojo),
            // render: value => this.Dict.userEnablePojo[value],
        },
        {
            field: 'themeType',
            title: '主题',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'themeTypes',
            filters: DictionConstUtil.PojoToList3(this.Dict.themeTypePojo),
            render: value => this.Dict.themeTypePojo[value],
        },
        {
            field: 'jobStatus',
            title: '在职状态',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'jobStatusTypes',
            filters: DictionConstUtil.PojoToList3(this.Dict.jobStatusPojo),
            // render: value => this.Dict.jobStatusPojo[value],
        },
        {
            field: 'lockType',
            title: '锁定类型',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filterField: 'lockTypes',
            filters: DictionConstUtil.PojoToList3(this.Dict.lockTypePojo),
            // render: value => this.Dict.lockTypePojo[value],
        },
        {
            field: 'beginLockTime',
            title: '锁定开始时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => this.handleDateAndTime(value),
            // render: (value, row) => value && moment(value, 'YYYYMMDDHHmmss').format('yyyy-MM-DD HH:mm:ss'),
        },
        {
            field: 'endLockTime',
            title: '锁定结束时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => this.handleDateAndTime(value),
            // render: (value, row) => value && moment(value, 'YYYYMMDDHHmmss').format('yyyy-MM-DD HH:mm:ss'),
        },
        { field: 'createUser', title: '创建人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'createDate',
            title: '创建时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.createTime)).trim(),
        },
        { field: 'modifyUser', title: '更新人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'modifyDate',
            title: '更新时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.modifyTime)).trim(),
        },
        { field: 'operation', fixed: 'right', title: '操作', align: 'center', width: '240px' },
    ];

    created() {
        this.getTableData();
        this.getAllMenu();
        this.getfundInfo();
        this.getRoleList();
    }

    // 角色已选项前置
    get computedRoleStorage() {
        let roleStorage = changeOptions(this.editRole, this.roleStorage, 'dictKey');
        return roleStorage;
    }

    // 获取所有角色列表
    private getRoleList(): void {
        this.roleStorage = [];
        this.$axios({ url: '/role/query/all' }).then((res: any) => {
            if (res && res.length) {
                // this.roleStorage = res;
                res.forEach(ele => {
                    this.roleStorage.push({ dictKey: ele.roleCode, dictKeyName: ele.roleName });
                });
            }
        });
    }

    private addDialog(): void {
        this.getuserCodeList('');
        this.dialogAdd = true;
        this.addRoleKeyNum++;
        this.addData = {
            userCode: '',
            userName: '',
            superuser: false,
            userNickName: '',
            password: '',
            email: '',
            userEnable: '1',
            themeType: '0',
            role: '',
        };
        this.passWord = '';
        this.addRole = [];
    }

    // 是否为管理员
    private changeSuperUser(value: string, type: string) {
        if (value) {
            this.customSelectReturn([], type);
            this.roleKeyNum++;
        }
    }

    // 新增用户
    private addUserInfo(): void {
        if (!this.addData.userName || !this.addData.userName.trim()) {
            this.yh_message_error('用户名不能为空');
            return;
        } else if (!this.addData.userNickName || !this.addData.userNickName.trim()) {
            this.yh_message_error('用户昵称不能为空');
            return;
        } else if (this.WEB_DOCKING != 'SINOSIG' && (!this.passWord || !this.passWord.trim())) {
            this.yh_message_error('密码不能为空');
            return;
        }
        if (!this.editData.userEnable) {
            this.yh_message_error('启用状态不能为空');
            return;
        }
        if (!this.addData.email || !this.addData.email.trim()) {
            this.yh_message_error('邮箱不能为空');
            return;
        }
        if (this.addData.email && this.addData.email.trim()) {
            var reg = new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$');
            if (!reg.test(this.addData.email)) {
                this.yh_message_error('邮箱格式不正确！');
                return;
            }
        }
        if (this.passWord.length < 8) {
            this.yh_message_error('密码长度不少于8位');
            this.passWord = '';
            return;
        }
        // 包含至少一个字母和一个数字的密码
        const pattern = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
        if (!pattern.test(this.passWord)) {
            this.yh_message_error('密码必须包含字母和数字');
            this.passWord = '';
            return;
        }

        this.addLoading = true;
        this.addData.password = md5(this.passWord + AuthenticationMd5Key);
        this.$axios
            .post('/userManage/insertUser/user', this.addData)
            .then(res => {
                this.yh_message_success('新增成功');
                this.addLoading = false;
                this.dialogAdd = false;
                this.passWord = '';
                this.addData = {
                    userCode: '',
                    userName: '',
                    superuser: false,
                    userNickName: '',
                    password: '',
                    email: '',
                    userEnable: '1',
                    themeType: '0',
                    role: '',
                };
                this.getTableData();
                this.refreshTable();
            })
            .catch(() => {
                this.addLoading = false;
                this.passWord = '';
                this.addData.password = '';
            });
    }

    // 判断  在复核状态中仍可编辑等操作，但不可删除
    judgeModifyStatus(val) {
        if (val.modifyStatus == '1') {
            return true;
        }
        return false;
    }

    judgeDialog() {
        let pro = this.$confirm(` <div style="text-align:center">已存在未复核记录，确定要修改吗？</div>`, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
        });
        return pro;
    }

    // 编辑获取详情
    private lookEditorInfo(val: any): void {
        console.log(val, 'val');
        if (this.judgeModifyStatus(val)) {
            const pro = this.judgeDialog();
            pro.then(() => {
                this.getuserCodeList(val.userName);
                this.lookEditorInfoReal(val);
            });
        } else {
            this.getuserCodeList(val.userName);
            this.lookEditorInfoReal(val);
        }
    }

    lookEditorInfoReal(val) {
        this.dialogEditor = true;
        this.editRole = val.roleCodes || [];
        this.editData = { ...val };
        this.editData.role = this.editData['roleCodes']?.join(',') || '';
        this.editData.password = '';
        this.roleKeyNum++;
    }

    // 提交编辑
    private editUserInfo(): void {
        if (!this.editData.userName || !this.editData.userName.trim()) {
            this.yh_message_error('用户名不能为空');
            return;
        }
        if (!this.editData.userNickName || !this.editData.userNickName.trim()) {
            this.yh_message_error('用户昵称不能为空');
            return;
        }
        if (!this.editData.email || !this.editData.email.trim()) {
            this.yh_message_error('邮箱不能为空！');
            return;
        }
        if (this.editData.email && this.editData.email.trim()) {
            var reg = new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$');
            if (!reg.test(this.editData.email)) {
                this.yh_message_error('邮箱格式不正确！');
                return;
            }
        }
        if (!this.editData.themeType) {
            this.yh_message_error('主题不能为空');
            return;
        }

        if (!this.editData.userEnable) {
            this.yh_message_error('启用状态不能为空');
            return;
        }

        if (this.editData.password && this.editData.password.length < 8) {
            this.yh_message_error('密码长度不少于8位');
            this.passWord = '';
            return;
        }
        // 包含至少一个字母和一个数字的密码
        const pattern = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
        if (this.editData.password && !pattern.test(this.editData.password)) {
            this.yh_message_error('密码必须包含字母和数字');
            this.passWord = '';
            return;
        }

        if (this.editData.password && this.editData.password.trim()) {
            this.editData.password = md5(this.editData.password + AuthenticationMd5Key);
        }

        this.editLoading = true;
        this.$axios({
            url: '/userManage/updateUser/user',
            method: 'POST',
            data: this.editData,
        })
            .then(res => {
                this.yh_message_success('编辑成功');
                this.getTableData();
                this.refreshTable();
                this.editRole = [];
                this.editLoading = false;
                this.dialogEditor = false;
            })
            .catch(() => {
                this.editLoading = false;
                this.editData.password = '';
            });
    }

    // 提交删除
    private removeUserInfo(): void {
        this.editLoading = true;
        this.$axios({
            url: '/userManage/delete/users',
            method: 'POST',
            data: this.deleteCode,
        })
            .then(res => {
                this.yh_message_success('删除成功');
                this.getTableData();
                this.refreshTable();
                this.editLoading = false;
                this.removeAlert = false;
            })
            .catch(() => {
                this.editLoading = false;
            });
    }

    // 获取删除的code
    private getUserInfo(code?: any): void {
        if (code) {
            this.deleteCode = [code];
        } else {
            const list = (this.$refs.multipleTable as any).checkedRows.filter(item => !item.superuser).map(item => item.userCode);
            this.deleteCode = list || [];
        }
        if (!this.deleteCode.length) {
            this.yh_message_error('请选择非管理员账号的删除项');
            return;
        }
        this.removeAlert = true;
    }
    // TODO
    searchParams: any = {
        keyOrName: '',
        sort: {
            field: '',
            order: '',
        },
    };

    search() {
        this.paging.currentPage = 1;
        this.getTableData();
    }
    // 分页
    private getTableData($event?: any) {
        if ($event && $event.type == 'sort') {
            this.searchParams.sort = {
                field: $event['sortField'],
                order: $event['order'],
            };
        }
        this.$axios.post('/userManage/query', { ...this.searchParams, paging: this.paging }).then((res: any) => {
            if (res) {
                res.list &&
                    res.list.forEach(ele => {
                        ele.roleName2 = ele.roleName ? ele.roleName.join(',') : '';
                    });

                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
                console.log(this.tableData, '-------------');
            }
        });
    }

    jurisdictionInfo(row: any): void {
        if (this.judgeModifyStatus(row)) {
            const pro = this.judgeDialog();
            pro.then(() => {
                this.jurisdictionInfoReal(row);
            });
        } else {
            this.jurisdictionInfoReal(row);
        }
    }

    // 权限用户id
    private jurisdictionInfoReal(row: any): void {
        this.dialogJurisdiction = true;

        this.currentUserInfo = row;

        this.userCode = row.userCode;
        // 权限
        this.getUserResource(row.userCode);
        // 基金
        this.getUserFund(row.userCode);
        // 是否拥有所有产品权限
        this.getUserHasAllPower(row.userCode);
        // console.log();
    }

    // 获取用户管理信息
    private getAllMenu(): void {
        this.$axios.get('/userManage/menu/queryAll').then((res: any) => {
            var menuAllList = [];
            this.treeData = res;
            this.getMenuList(res, menuAllList);
            this.menuAllOut = menuAllList;
        });
    }

    // 获取下级菜单获按钮 排除所有父级
    private getMenuList(data: any, menuAllOut: any): void {
        for (let item of data) {
            if (item.children && item.children.length > 0) {
                this.getMenuList(item.children, menuAllOut);
            } else {
                menuAllOut.push(item.resourceCode);
            }
        }
    }

    // 获取用户权限
    private getUserResource(val: string): void {
        this.$axios.get('/userManage/user/resource/' + val).then((res: any) => {
            this.menuAllList = res;
            // 过滤掉父级节点
            let nodeKye = res.filter((item: any) => this.menuAllOut.includes(item));
            let setKey = this.$refs.tree as { setCheckedKeys?: any };
            // setKey.setCheckedKeys(nodeKye);//
        });
    }

    // 是否拥有所有产品权限
    private handleAllProduct(value: boolean): void {
        this.riskTrantableKey++;
    }

    // 修改权限
    private editUserclick(): void {
        this.userCodeList = [];
        const rightData = (this.$refs.usertrantable as any).getRightAllData();
        rightData.map((itme: any) => {
            this.userCodeList.push({ fundCode: itme.fundCode });
        });
        this.Loading = true;
        let data;
        // if (this.isDisabled) {
        //     data = ['-1'];
        // } else {
        //     data = this.userCodeList;
        // }
        API.userUpdateFund({
            userCode: this.userCode,
            allFundStatus: this.isDisabled ? '1' : '0',
            fundResource: this.userCodeList,
            serialNo: this.currentUserInfo.serialNo,
        })
            .then(res => {
                this.yh_message_success('用户权限添加成功');
                this.getfundInfo();
                this.getTableData();
                this.refreshTable();
                this.dialogJurisdiction = false;
                this.Loading = false;
            })
            .catch(() => {
                this.Loading = false;
            });
        // let getKey = this.$refs.tree as { getCheckedKeys?: any };
        // // 获取到勾选的key
        // let onClick = getKey.getCheckedKeys();
        // // 获取父级权限
        // let getData = this.menuAllList.filter(itme => {
        //     return onClick.indexOf(itme) === -1;
        // });
        // let data = onClick.concat(getData);
        // 权限
        // this.$axios
        //     .post('/userManage/insert/user/menuList/' + this.userCode, data)
        //     .then(res => {
        //         // 产品
        //         this.$axios
        //             .post('/userManage/user/insert/fund/' + this.userCode, this.userCodeList)
        //             .then(res => {
        //                 this.yh_message_success('用户权限添加成功');
        //                 this.getfundInfo();
        //                 this.getTableData();
        //                 this.dialogJurisdiction = false;
        //                 this.Loading = false;
        //             })
        //             .catch(() => {
        //                 this.Loading = false;
        //             });
        //     })
        //     .catch(() => {
        //         this.Loading = false;
        //     });
    }

    //  查看用户下的基金
    private getUserFund(val: string): void {
        this.$axios.get('/userManage/user/fund/' + val).then((res: any) => {
            if (res) {
                this.rightTranData = res;
                // 取出缓存中的值，然后遍历删除右边有的数据
                this.leftTranData = JSON.parse(sessionStorage.getItem('risk-FundInfo'));

                let setArr = this.rightTranData;
                // 右侧值
                let arrTest = [];
                for (let i = 0; i < setArr.length; i++) {
                    let tempIndex = this.leftTranData.findIndex(item => item.fundCode === setArr[i].fundCode);
                    if (tempIndex > -1) {
                        arrTest.push(tempIndex);
                    }
                }
                for (let i = this.leftTranData.length - 1; i >= 0; i--) {
                    if (arrTest.includes(i)) {
                        this.leftTranData.splice(i, 1);
                    }
                }
                // this.isDisabled = !(this.leftTranData.length > 0);
            }
        });
    }

    // 用户是否拥有所有权限
    private getUserHasAllPower(val: string): void {
        this.$axios.post('/userManage/allFundStatus/' + val).then((res: any) => {
            this.isDisabled = res;
        });
    }

    // 所有的基金
    private getfundInfo(): void {
        let tmpe = JSON.parse(sessionStorage.getItem('risk-FundInfo'));
        if (tmpe) {
            return;
        } else {
            this.$axios.get('/fundInfo/list').then(res => {
                if (res) {
                    sessionStorage.setItem('risk-FundInfo', JSON.stringify(res));
                }
            });
        }
    }

    private customSelectReturn(values: any[], type: string): void {
        if (type === 'edit') {
            this.editRole = values;
            this.editData.roleCodes = values;
            this.editData.role = values.join(',');
        } else if (type === 'add') {
            this.addRole = values;
            this.addData.roleCodes = values;
            this.addData.role = values.join(',');
        }
    }

    private timeFormat = timeFormat;
    private dateFormat = dateFormat;
    currentUserInfo: any = {}; // 当前行info
    accessControlVisible: boolean = false;

    // 用户访问控制
    accessControl(row: any) {
        if (this.judgeModifyStatus(row)) {
            const pro = this.judgeDialog();
            pro.then(() => {
                this.accessControlReal(row);
            });
        } else {
            this.accessControlReal(row);
        }
    }

    accessControlReal(row: any) {
        this.currentUserInfo = row;
        this.accessControlVisible = true;
    }

    // 用户修改记录
    operateRecord(row: any) {
        this.currentUserInfo = row;
        this.dispatch('AuthManage', 'addTabs', row);
    }

    /**
     * 复选框是否可勾选
     */
    checkMethod({ row }) {
        //  TODO key值
        return row.modifyStatus != '1';
    }

    /**
     * 字段颜色处理 TODO  key值未确定
     */
    getTextColor(param: string, value: string) {
        if (param == 'userEnable') {
            if (value == '0') {
                return { color: 'red' };
            } else if (value == '1') {
                return { color: 'green' };
            }
        } else if (param == 'jobStatus') {
            if (value == '0') {
                return { color: 'red' };
            } else if (value == '1') {
                return { color: 'green' };
            }
        } else if (param == 'lockType') {
            if (value == '1') {
                // 锁定用户;
                return { color: 'red' };
            } else if (value == '2') {
                // 锁定用户;
                return { color: '#f5a578' };
            } else {
                return { color: 'green' };
            }
            // else if (value == '0') {
            //     // 未锁定
            //     return { color: 'green' };
            // }
        }
    }

    // 访问控制回调函数
    accessControlRet(type: string) {
        if (type == 'confirm') {
            // 重新获取数据
            console.log('getTableData++');
            this.getTableData();
            this.refreshTable();
        }
        this.accessControlVisible = false;
    }
    userReportState: boolean = false;
    timer = null;
    userReport = [];
    getuserCodeList(val: any) {
        if (this.WEB_DOCKING != 'SINOSIG') {
            return;
        }
        this.userReportState = true;
        try {
            clearTimeout(this.timer);
        } catch (e) {}
        this.timer = setTimeout(() => {
            API.importCustomerUserList({
                keyOrName: val,
                paging: { currentPage: 1, pageSize: 20 },
            })
                .then((res: any) => {
                    this.userReport = res?.list || [];
                    this.userReportState = false;
                })
                .catch(() => {
                    this.userReportState = false;
                });
        }, 300);
    }

    handleDateAndTime(values) {
        let retValue = '--';
        if (values) {
            let date = String(values).substring(0, 8);
            let time = String(values).substring(8);
            retValue = dateFormat(date) + '  ' + timeFormat(time);
        }
        return retValue;
    }

    // 刷新表格
    refreshTable() {
        this.$emit('refresh-list');
    }
}
</script>
<style lang="scss" scoped>
.user-manage {
    .manage-search {
        display: flex;
        border: 1px solid #eee;
        padding: 8px;

        .input-container {
            width: 200px;
            margin-right: 30px;
        }
    }

    .user-list-dialog {
        & /deep/ .el-form-item__label::after {
            color: red;
        }

        .list-dialog-form {
            width: 240px;
        }
    }

    .user-tables {
        & /deep/ .el-pagination {
            padding: 15px 0 0 0 !important;
        }

        .user-tables-div {
            & /deep/ .el-button--mini {
                padding: 2px 8px !important;
            }
        }

        .user-tables-editor {
            .list-dialog-form {
                width: 240px;
            }
        }

        .user-qx {
            .el-tabs__content {
                padding: 1px;

                .el-tab-pane {
                    color: #222;
                }
            }

            .uers-tabs {
                // margin-top: 10px;
                height: 470px;
                overflow-y: auto;
            }
        }

        & /deep/ .el-dialog {
            margin-top: 7vh !important;
            .el-dialog__body {
                // max-height: none;
                max-height: 70vh;
            }
        }

        & /deep/ .el-tabs .el-tabs__nav .el-tabs__item {
            line-height: 34px;
        }

        .remove-text {
            padding: 20px 10px;
        }
    }
}

.noOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 215px) !important;
    }
}

.el-icon-setting {
    color: green;
    margin-right: 5px;
}

.el-icon-delete {
    color: red;
    margin-right: 5px;
}

.el-icon-folder-add {
    color: green;
    margin-right: 5px;
}
</style>
